<script setup lang='ts'>
import { useBindCategory, useDelCategoryScheme, useEditCategoryScheme, useGetConfigCategory } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import { useMessage } from '@fl/hooks/web/use-message'
import { cloneDeep } from 'lodash-es'

import AddOrEdit from './add-or-edit.vue'
import BoundCategory from './bound-category.vue'

const { createConfirmModal, createMessage } = useMessage()
const { query } = useRoute()
const visible = ref<boolean>(false)
const showSecondLevel = ref<boolean>(false)
const showThreeLevel = ref<boolean>(false)
const boundVisible = ref<boolean>(false)
const router = useRouter()
const firstIdx = ref<number>(0)
const secondIdx = ref<number>(0)
const id = ref<string>('')
const parentId = ref<number>(0)

const HIDE_DICT = {
    0: {
        status: 1,
        tooltipLabel: '确认隐藏类目',
    },
    1: {
        status: 0,
        tooltipLabel: '确认显示类目',
    },
}

const treeData = ref([])

const params = computed(() => ({ configId: query.id }))
const { data: catagoryData } = useGetConfigCategory(params)
const { mutate: delCategorySchemeMutate } = useDelCategoryScheme()
const { mutate: editCategorySchemeMutate } = useEditCategoryScheme()
const { mutate: bindCategoryMutate } = useBindCategory()

watchEffect(() => {
    if (query.id) {
        if (catagoryData.value) {
            treeData.value = cloneDeep(catagoryData.value)
        }
    }
})

watchEffect(() => {
    if (treeData.value.length > 0) {
        parentId.value = treeData.value[firstIdx.value]?.id
    }
    else {
        showSecondLevel.value = false
        parentId.value = 0
    }
})

function getSelectData(item) {
    treeData.value[firstIdx.value].children[secondIdx.value].configMappings = item
}

function delSelection(index) {
    treeData.value[firstIdx.value].children[secondIdx.value].configMappings.splice(index, 1)
}

function selectFirstCategory(index: number) {
    firstIdx.value = index
    secondIdx.value = 0
    showThreeLevel.value = false
}

function selectSecondCategory(index: number) {
    secondIdx.value = index
}

function addLevel() {
    visible.value = true
}

function editCategoty(categoryId: any) {
    // 编辑类目
    id.value = categoryId
    visible.value = true
}

function hideCategoty(id: number, name: string, isHidden: number) {
    // 隐藏类目
    createConfirmModal({ content: `${HIDE_DICT[isHidden].tooltipLabel}:${name}？`, onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        editCategorySchemeMutate({
            id,
            isHidden: Number(HIDE_DICT[isHidden].status),
        }, {
            onSuccess: () => {
                ElMessage.success('操作成功')
            },
        })
    } })
}

function delCategoty(id: any) {
    // 删除类目
    createConfirmModal({ content: '是否确认删除？', onError: () => {
        console.log('操作取消！')
    }, onSuccess: () => {
        delCategorySchemeMutate(id, {
            onSuccess: () => {
                firstIdx.value = 0
                secondIdx.value = 0
                createMessage.success('删除成功')
            },
        })
    } })
}

function expandSecondLevel() {
    showSecondLevel.value = true
    console.log('展开二级类目')
}

function expandThreeLevel() {
    showThreeLevel.value = true
    console.log('展开二级类目')
}

function cancel() {
    // 返回
    router.push('/operations-pages/category-management/list')
}

function getConfigMappings(tree) {
    const result: any = []

    function traverse(node) {
        if (node.children && node.children.length > 0) {
            node.children.forEach((child) => {
                if (child.children && child.children.length > 0) {
                    traverse(child)
                }
                if (child.configMappings) {
                    result.push({
                        categoryIds: child.configMappings.map(item => item.categoryId),
                        displayId: child.id,
                    })
                }
            })
        }
    }

    traverse({ children: tree })
    return result
}

async function confirm() {
    console.log('树结构', treeData.value)
    const res = getConfigMappings(treeData.value)
    console.log('提交', res)
    bindCategoryMutate({ jcCategoryConfigMapping: res }, {
        onSuccess: () => {
            router.push('/operations-pages/category-management/list')
            createMessage.success('操作成功')
        },
    })
}
</script>

<template>
    <ElCard shadow="never">
        <div class="text-18">
            类目方案：{{ query.name }}
        </div>
    </ElCard>

    <ElCard shadow="never"
            class="mt-10"
    >
        <el-button type="primary"
                   class="mb-10"
                   @click="addLevel"
        >
            添加类目
        </el-button>

        <div class="category">
            <div class="level level-1">
                <div class="header pl-16 pr-16">
                    <div>一级类目</div>

                    <!-- <el-button type="primary"
                               @click="addLevel"
                    >
                        添加
                    </el-button> -->
                </div>

                <div class="level-content level1">
                    <div class="table">
                        <div class="table-head">
                            <div class="pl-16">
                                排序
                            </div>

                            <div class="pl-16">
                                类目名称
                            </div>
                        </div>

                        <div class="table-body">
                            <div v-for="(item, index) in treeData"
                                 :key="index"
                                 class="table-row"
                                 :class="{ active: firstIdx === index }"
                                 @click="selectFirstCategory(index)"
                            >
                                <div class="pl-16">
                                    {{ item.categorySort }}
                                </div>

                                <div class="pl-16">
                                    {{ item.categoryName }}
                                </div>

                                <div class="flex">
                                    <div class="pl-10"
                                         @click="editCategoty(item.id)"
                                    >
                                        <el-icon><Edit /></el-icon>
                                    </div>

                                    <div class="pl-10"
                                         @click="hideCategoty(item.id, item.categoryName, item.isHidden)"
                                    >
                                        <el-icon v-if="item.isHidden">
                                            <Hide />
                                        </el-icon>

                                        <el-icon v-else>
                                            <View />
                                        </el-icon>
                                    </div>

                                    <div class="pl-10"
                                         @click="delCategoty(item.id)"
                                    >
                                        <el-icon><Delete /></el-icon>
                                    </div>

                                    <div class="pl-10"
                                         @click="expandSecondLevel"
                                    >
                                        <el-icon><ArrowRight /></el-icon>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <transition name="el-zoom-in-center">
                <div v-if="showSecondLevel"
                     class="level level-2"
                >
                    <div class="header pl-16 pr-16">
                        <div>二级类目</div>

                        <!-- <el-button type="primary"
                                   @click="addLevel"
                        >
                            添加
                        </el-button> -->
                    </div>

                    <div class="level-content level2">
                        <div class="table">
                            <div class="table-head">
                                <div class="pl-16">
                                    类目名称
                                </div>
                            </div>

                            <div class="table-body">
                                <div v-for="(item, index) in treeData[firstIdx]?.children"
                                     :key="index"
                                     class="table-row"
                                     :class="{ active: secondIdx === index }"
                                     @click="selectSecondCategory(index)"
                                >
                                    <div class="pl-16">
                                        {{ item.categoryName }}
                                    </div>

                                    <div class="flex">
                                        <div class="pl-10"
                                             @click="editCategoty(item.id)"
                                        >
                                            <el-icon><Edit /></el-icon>
                                        </div>

                                        <div class="pl-10"
                                             @click="hideCategoty(item.id, item.categoryName, item.isHidden)"
                                        >
                                            <el-icon v-if="item.isHidden">
                                                <Hide />
                                            </el-icon>

                                            <el-icon v-else>
                                                <View />
                                            </el-icon>
                                        </div>

                                        <div class="pl-10"
                                             @click="delCategoty(item.id)"
                                        >
                                            <el-icon><Delete /></el-icon>
                                        </div>

                                        <div class="pl-10"
                                             @click="expandThreeLevel"
                                        >
                                            <el-icon><ArrowRight /></el-icon>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </transition>

            <transition name="el-zoom-in-center">
                <div v-if="showThreeLevel"
                     class="level level-3"
                >
                    <div class="header pr-16 justify-end!">
                        <el-button type="primary"
                                   @click="boundVisible = true"
                        >
                            绑定后台类目
                        </el-button>
                    </div>

                    <div class="level-content level3">
                        <div class="table">
                            <div class="table-head">
                                <div class="pl-16">
                                    序号
                                </div>

                                <div class="pl-16">
                                    后台类目路径
                                </div>

                                <div class="pl-16">
                                    商品数量
                                </div>

                                <div>
                                    操作
                                </div>
                            </div>

                            <div class="table-body">
                                <div v-for="(item, index) in treeData[firstIdx]?.children[secondIdx].configMappings"
                                     :key="index"
                                     class="table-row"
                                >
                                    <div class="pl-16">
                                        {{ index + 1 }}
                                    </div>

                                    <div class="pl-16 truncate"
                                         :title="item.categoryPath"
                                    >
                                        {{ item.categoryPath }}
                                    </div>

                                    <div class="pl-16">
                                        {{ item.productNum }}
                                    </div>

                                    <div class="text-blue-500 cursor-pointer"
                                         @click="delSelection(index)"
                                    >
                                        删除
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </transition>
        </div>
    </ElCard>

    <AddOrEdit :key="id"
               v-model:configId="query.id"
               v-model:parentId="parentId"
               v-model:visible="visible"
               v-model:id="id"
               :tree-data="treeData"
    />

    <BoundCategory v-model:boundVisible="boundVisible"
                   @select-data-change="getSelectData"
    />

    <div class="footer">
        <div>
            <el-button @click="cancel">
                返回
            </el-button>

            <SubmitBtn type="primary"

                       @click="confirm"
            >
                提交
            </SubmitBtn>
        </div>
    </div>
</template>

<style scoped lang='less'>
.category {
    display: flex;
    overflow-x: auto;
    .level {
        width: 370px;
        height: calc(100vh - 360px);
        border: 1px solid #dcdfe6;
        margin-right: 10px;
        .header {
            width: 100%;
            height: 40px;
            overflow: hidden;
            border-bottom: 1px solid #dcdfe6;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .level-content {
            width: 100%;
            height: calc(100% - 40px);
            overflow: auto;
            .table {
                width: 100%;
                height: 100%;
                .table-head {
                    width: 100%;
                    height: 36px;
                    overflow: hidden;
                    display: grid;
                    grid-template-columns: 44px 211px 115px;
                    align-items: center;
                    background: #f5f6fa;
                }
                .table-body {
                    .table-row {
                        width: 100%;
                        height: 36px;
                        overflow: hidden;
                        display: grid;
                        grid-template-columns: 44px 211px 115px;
                        align-items: center;
                        cursor: pointer;
                        &.active {
                            background: #fbe5e5;
                        }
                    }
                }
            }
            &.level1 {
                .table-body {
                    .table-row {
                        &:hover {
                            background: #fbe5e5;
                        }
                    }
                }
            }
            &.level2 {
                .table-head {
                    grid-template-columns: 255px 115px !important;
                }
                .table-body {
                    .table-row {
                        &:hover {
                            background: #fbe5e5;
                        }
                        grid-template-columns: 255px 115px !important;
                    }
                }
            }
            &.level3 {
                .table-head {
                    grid-template-columns: 65px 130px 130px 45px !important;
                }
                .table-body {
                    .table-row {
                        grid-template-columns: 65px 130px 130px 45px !important;
                        border-bottom: 1px solid #dcdfe6;
                    }
                }
            }
        }
    }
}
.footer {
    width: 100%;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    position: fixed;
    height: 60px;
    margin-top: 10px;
}
</style>
